import { useState, useEffect, useCallback } from 'react';
import { MOCK_ROLES, MOCK_PERMISSIONS, PermissionCode } from '../types/auth';

// 获取用户信息
const getCurrentUser = () => {
  const userStr = localStorage.getItem('adminUser');
  if (!userStr) return null;
  return JSON.parse(userStr);
};

// 获取用户角色
const getUserRoles = (roleIds: string[]) => {
  return MOCK_ROLES.filter(role => roleIds.includes(role.id));
};

// 获取角色权限
const getRolePermissions = (roleIds: string[]) => {
  const roles = MOCK_ROLES.filter(role => roleIds.includes(role.id));
  const permissionIds = roles.flatMap(role => role.permissions);
  return MOCK_PERMISSIONS.filter(permission => 
    permissionIds.includes(permission.id)
  );
};

export const useAuth = () => {
  const [currentUser, setCurrentUser] = useState<any>(null);
  const [userRoles, setUserRoles] = useState<any[]>([]);
  const [userPermissions, setUserPermissions] = useState<any[]>([]);
  const [isInitialized, setIsInitialized] = useState(false);

  // 从 localStorage 获取用户信息
  useEffect(() => {
    const initializeAuth = () => {
      const storedUser = localStorage.getItem('adminUser');
      if (storedUser) {
        try {
          const user = JSON.parse(storedUser);
          setCurrentUser(user);
          
          // 获取用户角色
          const roles = MOCK_ROLES.filter(role => user.roles.includes(role.id));
          setUserRoles(roles);
          
          // 获取用户权限
          const permissionIds = roles.flatMap(role => role.permissions);
          const permissions = MOCK_PERMISSIONS.filter(permission => 
            permissionIds.includes(permission.id)
          );
          setUserPermissions(permissions);
        } catch (error) {
          // 如果解析失败，清除可能损坏的数据
          localStorage.removeItem('adminUser');
          localStorage.removeItem('adminToken');
        }
      }
      setIsInitialized(true);
    };

    initializeAuth();
  }, []);

  // 检查是否有指定权限
  const hasPermission = useCallback((permissionCode: PermissionCode) => {
    if (!isInitialized) return false;
    return userPermissions.some(p => p.code === permissionCode);
  }, [userPermissions, isInitialized]);

  // 检查是否有任意一个权限
  const hasAnyPermission = useCallback((permissionCodes: PermissionCode[]) => {
    if (!isInitialized) return false;
    return permissionCodes.some(code => hasPermission(code));
  }, [hasPermission, isInitialized]);

  // 检查是否有所有权限
  const hasAllPermissions = useCallback((permissionCodes: PermissionCode[]) => {
    if (!isInitialized) return false;
    return permissionCodes.every(code => hasPermission(code));
  }, [hasPermission, isInitialized]);

  // 检查是否是超级管理员
  const isSuperAdmin = useCallback(() => {
    if (!isInitialized) return false;
    return userRoles.some(role => role.id === '1');
  }, [userRoles, isInitialized]);

  // 退出登录
  const logout = useCallback(() => {
    localStorage.removeItem('adminToken');
    localStorage.removeItem('adminUser');
    setCurrentUser(null);
    setUserRoles([]);
    setUserPermissions([]);
    setIsInitialized(false);
  }, []);

  return {
    currentUser,
    userRoles,
    userPermissions,
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    isSuperAdmin,
    logout,
    isInitialized
  };
}; 